package org.splink.library.logging.logoutput.qlogutils {
	import org.splink.library.logging.ILogger;
	import org.splink.library.logging.LoggerProvider;
	import org.splink.library.logging.logoutput.QLogOutput;
	import org.splink.library.tree.INode;
	import org.splink.library.tree.Node;
	import org.splink.library.tree.Tree;

	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;

	/**
	 * Recurses through the flash Displaylist and builds a <code>Tree</code> from it. The tree is
	 * serialized into xml and sent to QLog. QLog itself opens a new tab or refreshes an already 
	 * opened tab with the same name and displays the xml as a navigatable tree. 
	 * 
	 * @author Max Kugland
	 */
	public class DisplaylistTree {
		private var _logger : ILogger;
		private var _tabName : String;

		/**
		 * @param displayObject any <code>DisplayObjectContainer</code> which will serve as the root
		 * node of the tree.
		 * @param logFactoryId the id for the <code>ILoggerFactory</code> you wish to use to send
		 * the data to QLog
		 * @param tabName the name of the tab in QLog
		 */
		public function DisplaylistTree(root : DisplayObjectContainer, logFactoryId : String, tabName : String = "DisplayList") {
			_tabName = tabName;
			_logger = LoggerProvider.getLogger(logFactoryId, DisplaylistTree);
			
			update(DisplayObjectContainer(root));
		}

		/**
		 * Updates the <code>Tree</code> and sends the result to QLog
		 * 
		 * @param displayObject any <code>DisplayObjectContainer</code> which will serve as the root
		 * node of the tree.
		 */
		public function update(root : DisplayObjectContainer) : Tree {
			var tree : Tree = new Tree(new Node("DisplayList", null));
			recurse(root, tree.root);
			
			var xml : XML = Tree.toXml(tree, tree.root.id, null);
			QLogOutput(_logger.getLogOutput(QLogOutput)).sendXmlTree(xml, _tabName);
			
			return tree;
		}

		private function recurse(container : DisplayObjectContainer, node : INode) : void {
			for (var i : int = 0;i < container.numChildren; i++) {
				var obj : DisplayObject = container.getChildAt(i);
				
				var n : INode = new Node("ı" + obj.name, node);
				node.add(n);
				
				if(obj is DisplayObjectContainer) {
					recurse(DisplayObjectContainer(obj), n);
				}
			}
		}
	}
}